<template>
  <div style="height: 90vh;">
    <a-card :title="title">
      <SchemaForm>
      </SchemaForm>
      <div style="text-align: center;">
        <Space>
          <AButton color="rgb(64,169,255)" :disabled="openHandleButton" @click="openHandleModel"> 处理 </AButton>
          <AButton color="rgb(64,169,0)" @click="processHisvisibleModel"> 流转历史 </AButton>
          <AButton color="rgb(64,169,255)" @click="goBack">
            返回
          </AButton>
        </Space>
      </div>
    </a-card>
    <DraggableModal v-model:visible="processHisvisible" title="流转历史" :body-style="{maxHeight:'50vh',overflowY: 'auto'}" :centered=false width="60%"
      :keyboard="false" :fullscreen=false :closable=true footer="">
      <processHistory :replyShow ="false" :extension-show="false" :superviseShow="false" :returnVisitShow="false" :work-order-number="superviseObj.workOrderNumber" :instance-id="superviseObj.instanceId"></processHistory>
    </DraggableModal>
  </div>
</template>

<script lang="ts" setup>
import { Space } from 'ant-design-vue';
import { useForm } from '@/components/core/schema-form';
import { AButton } from '@/components/basic/button';
import { reactive, ref, onMounted } from 'vue';
import { DraggableModal } from '@/components/core/draggable-modal';
import { useFormModal } from '@/hooks/useModal/useFormModal';
import { getSupervise, approveSupervise } from '@/api/workorder/supervise';
import { listAttament } from '@/api/workorder/common/attachment';
import { superviseschemas } from './formSchemas';
import { useRoute,useRouter } from 'vue-router';
import { useTabsViewStore } from '@/store/modules/tabsView';
import { checkUserIdDoTask, getTaskListByProcessInstanceId } from '@/api/workorder/task';
import { approveschemas } from '@/views/workorder/common/approveFormSchemas';
import { any } from 'vue-types';
import processHistory from '@/views/workorder/task/processHistory/index.vue';
import { workorderschemas } from '@/views/workorder/order/formSchemas';
import { getWorkOrderByWorkOrderNumber } from '@/api/workorder/order';

defineOptions({
  name: 'todoSupervise',
});
// 工单信息
let superviseObj = reactive([]);
// 打开回复页面
const [showModal] = useFormModal();
const route = useRoute();
const router = useRouter();

const tabsViewStore = useTabsViewStore();
// 办理页面按钮隐藏
const isTodoPage = ref(true);
// 审核按钮是否禁用
const openHandleButton = ref(true)
// biaoti
const title = ref('')
// 审批流程数据
let tasks = reactive(any);
// 正在进行的流程数据
const runningTasks = reactive([]);
// 流转历史是否显示
const processHisvisible = ref(false);


// 代办任务处理详情页面
onMounted(async () => {
  if (route.query.itemId) {
    // 按钮处理业务 1
    isTodoPage.value = false
    title.value = '待办处理'
    superviseObj = await getSupervise(route.query.itemId);
    let workorder = await getWorkOrderByWorkOrderNumber(superviseObj.workOrderNumber);
    tabsViewStore.updateTabTitle(superviseObj.superviseNo);
    // 保存工单信息后数据返填回去
    await dynamicFormRef?.setFieldsValue({
      ...superviseObj,
      ...workorder

    });
    // 添加附件列表(延期申请)
    let data = await listAttament({ 'bussId': route.query.itemId });
    let initFileData = [];
    data.forEach((fileData) => {
      initFileData.push({
        uid: fileData.id,
        name: fileData.fileName,
        status: 'done',
      });
    })
    dynamicFormRef?.updateSchema({
      field: 'attamentDb',
      componentProps: {
        fileList: initFileData
      },
    })
    // 添加附件列表(工单)
    let dataWorkOrder = await listAttament({ 'bussId': workorder.id });
    let initFileDataWorkOrder = [];
    dataWorkOrder.forEach((fileData) => {
      initFileDataWorkOrder.push({
        uid: fileData.id,
        name: fileData.fileName,
        status: 'done',
      });
    })
    dynamicFormRef?.updateSchema({
      field: 'attament',
      componentProps: {
        fileList: initFileDataWorkOrder
      },
    })
    // 禁用审核按钮
    if( superviseObj.approveStatus == 1){
      openHandleButton.value = false
    }

    // 加载流程审批信息
    await initProcessData();
    // 禁用表单数据
    disableForm();
    // 验证是否可以处理单据
    openHandleButton.value = !await checkUserIdDoTask(runningTasks[0].id)
  }
});

// 初始化表单内容
const [SchemaForm, dynamicFormRef] = useForm({
  labelWidth: 100,
  schemas: [{
    field: 'divider-basic',
    component: 'Divider',
    label: '工单信息',
  }, ...workorderschemas, ...superviseschemas],
  showSubmitButton: false,
  showResetButton: false,
});

// 加载流程任务数据
async function initProcessData() {
  tasks = await getTaskListByProcessInstanceId({ 'processInstanceId': superviseObj.instanceId });
  tasks.forEach(task => {
    if (task.result !== 1) { // 只有待处理才需要
      return;
    }
    runningTasks.push({ ...task });
  })
  console.log(runningTasks)
}


/**
 * @description 生成工单并派单（根据工单状态信息权限显示具体操作按钮）
 */
async function openHandleModel() {
  const [approveFormRef] = await showModal({
    modalProps: {
      title: `审核`,
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值督办单编号（感觉id比较合适 ~~~）
        values.superviseNo = dynamicFormRef?.getFieldsValue().superviseNo;
        // 赋值工单单号
        values.workOrderNumber = superviseObj.workOrderNumber;
        // 赋值任务单号
        values.taskId = runningTasks[0].id;
        values.definitionKey = runningTasks[0].definitionKey;
        // 默认同意
        values.result = 2
        // 任务处理
        await approveSupervise(values);
        setTimeout(() => { window.location.reload() }, 1500);
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: approveschemas,
    },
  });
  approveFormRef?.updateSchema({
    field: 'result',
    vShow: false
  })
}
/**
 * @description 流转历史表
 */
async function processHisvisibleModel() {
  // 打开操作框选择页面
  processHisvisible.value = true;
}

// 禁用表单
function disableForm() {
  dynamicFormRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
}


const goBack = async () => {
  router.go(-1)
}


</script>
<style lang="less">
  input,.ant-select-selection-item,textarea{
    color: black !important;
  }
  .ant-radio-disabled+span{
    color: black !important;
    cursor:text !important;
  }
</style>